// pages/Systems/Shares/Shares.js
//获取应用实例
const app = getApp();
import { queryAppInforMation , getQrCode } from '../../../api/brand';
import { getUser } from '../../../api/user';
import { toHttps } from '../../../utils/util';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    shareTitle: app.globalData.global.shareTitle,
    qrCode: '',
    user: {},
    swiperIndex: 0,
    shareList: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this._getShareUrl();
    this._getShare();
    this.getUser();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let userId = wx.getStorageSync('userId')
    return {
      title: this.data.shareTitle,
      path: '/pages/Welcome/Welcome?scene='+userId,
    }
  },
  // 获取分享图信息
  _getShare(){
    let _this = this;
    queryAppInforMation({infoType: '4'})
    .then(res => {
      if(res.success){
        _this.setData({
          shareList: res.data.content,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取小程序分享链接
  _getShareUrl(){
    let _this = this;
    let userId = wx.getStorageSync('userId')
    var path = 'pages/Welcome/Welcome?scene=' + userId;
    getQrCode({path: path})
    .then(res => {
      if(res.success){
        // console.log(res,'res')
        _this.setData({
          qrCode: `data:image/png;base64,${res.data}`,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取用户个人信息
  getUser(){
    let _this = this;
    getUser()
    .then(res => {
      if(res.success){
        _this.setData({
          user: res.data,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  createCanvas() { // 生成分享图片
    wx.showLoading({
      title: '加载中',
    })
    let _this = this;
    function roundRect(ctx, x, y, w, h, r) {
      if (w< 2 * r) r = w / 2;
      if (h < 2 * r) r = h / 2;
      ctx.moveTo(x + r, y);
      ctx.arcTo(x + w, y, x + w, y + h, r);
      ctx.arcTo(x + w, y + h, x, y + h, r);
      ctx.arcTo(x, y + h, x, y, r);
      ctx.arcTo(x, y, x + w, y, r);
      ctx.clip()
      ctx.fillRect(0, 0, 240, 427);
    }
    return new Promise((resolve, reject) => {
      let { shareList, swiperIndex , qrCode , user} = this.data;
      let item = shareList[swiperIndex] || null;
      // console.log(item,'item')
      // console.log(qrCode,'qrCode')
      Promise.all([
        // _this.downloadImg('./images/downloadIcon.png'),
        _this.downloadImg(item.imgUrl),
        _this.base64ToSrc(qrCode),
        _this.downloadImg(user.headimgurl), // TODO
      ]).then(res => {
        let ctx = wx.createCanvasContext('mycanvas');
        ctx.setFillStyle("#fff");
        // roundRect(ctx, 0, 0, 240, 427, 4) // 原始
        roundRect(ctx, 0, 0, 750, 1334, 4)
        ctx.restore();
        ctx.save();
        ctx.beginPath();
        // ctx.drawImage(res[0], 0, 0, 750, 357) // 原始
        ctx.drawImage(res[0], 0, 0, 750, 1115.625) 
        // 底部白色背景
        ctx.rect(0, 1115.625, 750, 1334 - 1115.625)
        ctx.setFillStyle('#FFFFFF')
        ctx.fill()
        // ctx.drawImage(res[1], 58, 357 + 12.5, 45, 45) TODO  // 原始
        // ctx.drawImage(res[1], 181.25, 1115.625 + 39.0625, 140.625, 140.625)
        ctx.closePath();
        ctx.drawImage(res[1], 511.25, 1115.625 + 39.0625, 140.625, 140.625)
        ctx.draw(true);
        ctx.restore();
        ctx.save();
        // ctx.setFontSize(30)
        // ctx.setFillStyle("#333333")
        // ctx.fillText("长按识别二维码", 353.125, 1115.625 + 46.875 + 46.875); // 原始
        // x:圆形中心点X坐标  y:圆形中心点Y坐标   r:圆形半径
        ctx.beginPath();
        let x = 53.125 + (70.625 / 2) ;
        let y = 1115.625 + 39.0625 + (70.625 / 2);
        let r = 70.625 / 2
        ctx.arc(x,y,r,0,2* Math.PI,false);
        ctx.clip();
        ctx.closePath();
        ctx.drawImage(res[2], 53.125, 1115.625 + 39.0625, 70.625, 70.625)
        ctx.draw(true);
        ctx.restore();
        ctx.setFontSize(30)
        ctx.setFillStyle("#999999")
        // ctx.fillText("邀请您加入我们", 113, 357 + 15 + 34); // 原始
        ctx.fillText("邀请好友登录，领取大额红包", 53.125, 1115.625 + 46.875 + 106.25); // 原始
        ctx.draw(true, setTimeout(() => {
          wx.canvasToTempFilePath({//导出图片
            // width: 240,
            // height: 427,
            width: 750,
            height: 1334,
            destWidth: 1500,
            destHeight: 2668,
            canvasId: 'mycanvas',
            fileType: 'png',
            success: res => {
              this.setData({
                shareImg: res.tempFilePath
              })
              resolve(res.tempFilePath)
            },
            fail: _ => {
              reject(null)
              wx.hideLoading({
                success: (res) => {},
              })
            }
          },this)
        }, 300))
      })
    })
  },
  downloadImg(url) {
    console.log(url,'url')
    return new Promise((resolve, reject) => {
      wx.getImageInfo({
        src: url,
        success: function (res) {
          // console.log(res,'res图片下载')
          resolve(res.path)
        },
        fail: function(err){
          console.log(err,'err')
          reject()
        },
      })
    })
  },
  shareHandle() { // 分享
    this.createCanvas().then(res => {
      wx.showShareImageMenu({
        path: res,
        fail: function(){
          wx.showToast({
            title: '已取消',
            icon: 'none',
          })
        }
      })
    })
  },
  saveImage() { // 保存图片
    this.createCanvas().then(res => {
      console.log('res', res)
      wx.saveImageToPhotosAlbum({
        filePath: res,
        success() {
          wx.showToast({
            title: '保存成功',
            icon: 'none',
          })
        },
        fail(err) {
          console.log(err,'err')
          wx.showToast({
            title: '保存失败',
            icon: 'none',
          })
        }
      })
    })
  },
  // base64转换成图片
  base64ToSrc(base64){
    base64 = base64.replace(/^data:image\/\w+;base64,/,'');
    let _this = this;
    var filePath = wx.env.USER_DATA_PATH + '/base64QrCode.png'
    return new Promise((resolve,reject) => {
      var fsm = wx.getFileSystemManager();
      fsm.writeFile({
        filePath: filePath,
        data: base64,
        encoding: 'base64',
        success: (res) => {
          resolve(filePath);
        },
        fail: function(err){
          console.log(err,'base64err')
          reject()
        },
      })
    })
  }
})